package com.xuanxuan.socketdemo.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.xuanxuan.socketdemo.R;
import com.ywicc.commlibs.bluetooth.BluetoothUtils;

import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;

public class BluetoothServerActivity extends AppCompatActivity {

    private final static String TAG = "BluetoothServerActivity";

    private BluetoothUtils utils;
    private String tmpString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bluetooth_server_activity);

        utils = new BluetoothUtils();
        try {
            utils.initBluetooth();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void btn_bluetooth_server(View view) {
        utils.onStartServer(new BluetoothUtils.BluetoothUtilsServerImpl() {
            @Override
            public void callBackServerData(byte[] data) {
                Log.w(TAG, new String(data, StandardCharsets.UTF_8));

                tmpString = new String(data, StandardCharsets.UTF_8);
            }
        });
    }

    public void btn_bluetooth_server_stop(View view) {
        utils.stopServer();
    }

    public static class BluetoothServerHandler extends Handler {
        private WeakReference<BluetoothServerActivity> weakActivity;

        public BluetoothServerHandler(BluetoothServerActivity activity, Looper looper) {
            super(looper);

            weakActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Toast.makeText(weakActivity.get(), weakActivity.get().tmpString, Toast.LENGTH_SHORT).show();
        }
    }
}